import { Component, OnInit, ViewChild, Injector, ViewEncapsulation } from '@angular/core';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { AppComponentBase } from '@shared/common/app-component-base';
import { Table } from 'primeng/table';
import { Paginator, LazyLoadEvent } from 'primeng/primeng';
import { StatisticsOfExecutionServiceProxy, ExecuteGroupByMainTaskOutput } from '@shared/service-proxies/service-proxies';
//import { ExcelModalComponent } from '@app/shared/common/excel-modal/excel-modal.component';
import * as moment from 'moment';
import { BsDatepickerViewMode } from 'ngx-bootstrap/datepicker/models';
import { BsDatepickerConfig } from 'ngx-bootstrap';
import { finalize } from 'rxjs/operators';
import { PrimengTableHelper } from '@shared/helpers/PrimengTableHelper';



@Component({
  templateUrl: './statistics.component.html',
  styleUrls: ['./statistics.component.css'],
  encapsulation: ViewEncapsulation.None,
  animations: [appModuleAnimation()]

})
export class StatisticsComponent extends AppComponentBase implements OnInit {
  bsValue: Date;
  minMode: BsDatepickerViewMode = 'month';
  bsConfig: Partial<BsDatepickerConfig>;
  workshoFilter: string = '';
  onlyHaveNotRoutes = false;
  rowGroupMetadata: any;

  processExecutionInfos: ExecuteGroupByMainTaskOutput[] = [];
  primengTableHelperExecution = new PrimengTableHelper();

  @ViewChild('dataTable') dataTable: Table;
  @ViewChild('paginatorExecution') paginator: Paginator;


  workShopList = [
    { value: '51', displayText: '51' },
    { value: '53', displayText: '53' },
    { value: '55', displayText: '55' },
    { value: '56', displayText: '56' },
    { value: '57', displayText: '57' },
    { value: '58', displayText: '58' }
  ];

  ngOnInit(): void {
    this.bsConfig = Object.assign({}, {
      minMode: this.minMode,
      dateInputFormat: 'MM-YYYY',
      returnFocusToInput: true
    });
    this.bsValue = null;
  }




  constructor(
    injector: Injector,
    private _statisticsOfExecutionServiceProxy: StatisticsOfExecutionServiceProxy
  ) {
    super(injector);

  }

  statisticLaborHour() {
    if (this.bsValue == null) {
      this.message.warn('请选择月份，再进行统计！');
    } else {
      this.paginator.changePage(0);
    }
  }

  clickSaveLaborHour() {
    if (this.bsValue == null) {
      this.message.warn('请选择月份，再进行保存！');
    } else {
      this._statisticsOfExecutionServiceProxy
        .checkHaveHourForMonth((moment)(this.bsValue))
        .subscribe(result => {
          if (result) {
            this.message.confirm(
              '已存在' + this.bsValue.getFullYear() + '年 ' + (this.bsValue.getMonth() + 1) + '月 的工时数据，是否需要覆盖？',
              this.l('AreYouSure'),
              isConfirmed => {
                this.saveLaborHour();
              }
            );

          } else {
            this.saveLaborHour();
          }
        }
        )



    }
  }

  saveLaborHour() {
    this.primengTableHelperExecution.showLoadingIndicator();
    this._statisticsOfExecutionServiceProxy
      .saveLaborHourForMonth((moment)(this.bsValue))
      .pipe(finalize(() => this.primengTableHelperExecution.hideLoadingIndicator()))
      .subscribe(result => {
        if (result == '' || result == null) {
          this.message.success('保存成功');
        } else {
          this.message.warn('保存失败，请检查后！<br>' + result);
        }
        this.primengTableHelperExecution.hideLoadingIndicator();
      }
      );
  }

  updateRowGroupMetaData(event?: LazyLoadEvent) {
    this.primengTableHelperExecution.showLoadingIndicator();
    this.rowGroupMetadata = {};

    this._statisticsOfExecutionServiceProxy
      .getAllExecuteGroupByMainTask(
        (moment)(this.bsValue),
        this.workshoFilter,
        this.onlyHaveNotRoutes,
        '',
        '',
        this.primengTableHelperExecution.getMaxResultCount(this.paginator, event),
        this.primengTableHelperExecution.getSkipCount(this.paginator, event)
      ).subscribe(result => {
        this.primengTableHelperExecution.totalRecordsCount = result.totalCount;
        this.primengTableHelperExecution.records = result.items;

        this.processExecutionInfos = result.items;
        this.primengTableHelperExecution.hideLoadingIndicator();

        if (this.processExecutionInfos) {
          for (let i = 0; i < this.processExecutionInfos.length; i++) {
            let rowData = this.processExecutionInfos[i];
            let mainTaskCode = rowData.mainTaskCode;
            if (i == 0) {
              this.rowGroupMetadata[mainTaskCode] = { index: 0, size: 1 };
            }
            else {
              let previousRowData = this.processExecutionInfos[i - 1];
              let previousRowGroup = previousRowData.mainTaskCode;
              if (mainTaskCode === previousRowGroup)
                this.rowGroupMetadata[mainTaskCode].size++;
              else
                this.rowGroupMetadata[mainTaskCode] = { index: i, size: 1 };
            }
          }
        }
      });
  }


}